package servlet.universal;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import dao.domain.Client;
import dao.domain.Order;
import service.OrderService;
import service.UserService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author gzb
 */
@WebServlet(name = "ClientReturnServlet", value = "/ClientReturnServlet")
public class ReturnOrdersServlet extends HttpServlet {

    /**
     * 把订单转换成json格式，且格式化时间
     *
     * @param orders 传入的订单列表
     * @return json格式化后的订单
     */
    public static String getJsonData(List<Order> orders) {
        Gson gson = new Gson();
        Map<String, Object> ordersMap = new HashMap<>(1);
        if (orders != null && !orders.isEmpty()) {
            List<JsonObject> formattedOrders = new ArrayList<>();
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (Order order : orders) {
                JsonObject jsonObject = gson.toJsonTree(order).getAsJsonObject();
                Date orderDate = order.getOrderDate();
                String formattedOrderDate = dateFormat.format(orderDate);
                jsonObject.addProperty("orderDate", formattedOrderDate);
                formattedOrders.add(jsonObject);
            }
            ordersMap.put("orders", formattedOrders);
        }
        return gson.toJson(ordersMap);
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Client client;
        List<Order> orders = null;
        try {
            client = (Client) UserService.selectByAccount("client", UserService.getAccountFromCookie(request));
            String userType1 = "client";
            String userType2 = "assistant";
            if (Objects.equals(UserService.getUserFromCookie(request), userType1)) {
                orders = OrderService.selectByClient(client);
            } else if (Objects.equals(UserService.getUserFromCookie(request), userType2)) {
                orders = OrderService.selectAll();
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        String jsonData = getJsonData(orders);
        response.getWriter().write(jsonData);
        System.out.println("finish");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("ClientReturnServlet现在来了一个post请求，将要去走get的代码了。");
        doGet(request, response);
    }
}
